<template>
  <view class="recommend-container">
    <!-- 返回按钮 -->
    <view class="back-btn" @click="goBack">
      <uni-icons type="back" size="20" color="white"></uni-icons>
    </view>

    <!-- 头部标题 -->
    <view class="header">
      <text class="title">行程智能规划</text>
      <text class="subtitle">根据您的偏好生成专属路线</text>
    </view>

    <!-- 需求采集表单 -->
    <view class="form-card">
      <view class="form-item">
        <text class="label">旅行时间</text>
        <picker mode="selector" :range="seasonOptions" @change="bindSeasonChange">
          <view class="input">{{ state.selectedSeason || '请选择旅行时间' }}</view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">出行人数</text>
        <view class="number-selector">
          <button class="btn-minus" @click="changePeopleCount(-1)">-</button>
          <text class="number">{{ state.peopleCount }} 人</text>
          <button class="btn-plus" @click="changePeopleCount(1)">+</button>
        </view>
      </view>

      <view class="form-item">
        <text class="label">旅行偏好</text>
        <view class="radio-group">
          <label v-for="tag in preferenceTags" :key="tag.value" class="radio-item">
            <radio 
              :value="tag.value" 
              :checked="state.selectedPreference === tag.value"
              @click="selectPreference(tag.value)"
              color="#4a8cff"
            />
            <text>{{ tag.label }}</text>
          </label>
        </view>
      </view>

      <view class="form-item">
        <text class="label">预算范围</text>
        <input 
          type="number" 
          v-model="state.budget" 
          placeholder="请输入预算范围" 
          class="budget-input"
        />
      </view>
    </view>

    <!-- 生成按钮 -->
    <button class="generate-btn" @click="generatePlan">生成推荐行程</button>

    <!-- 推荐结果 -->
    <view v-if="state.recommendations.length > 0" class="result-container">
      <text class="section-title">为您推荐的行程</text>
      
      <!-- 行程卡片 -->
      <view v-for="(item, index) in state.recommendations" :key="index" class="plan-card">
        <text class="plan-title">{{ item.destination }} · {{ item.duration }}</text>
        
        <view class="plan-detail">
          <view class="detail-item">
            <text class="detail-label">目的地:</text>
            <text class="detail-content">{{ item.destinationDescription }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">住宿:</text>
            <text class="detail-content">{{ item.accommodation }} - {{ item.accommodationDescription }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">交通:</text>
            <text class="detail-content">{{ item.transport }} - {{ item.transportDescription }}</text>
          </view>
          
          <view class="cost-info">
            <text class="cost-label">总预算:</text>
            <text class="cost-value">¥{{ item.totalCost }}</text>
            <text class="cost-people">({{ item.peopleCount }}人)</text>
          </view>
        </view>
      </view>

       <!-- 分页控件 -->
        <view class="pagination">
          <button @click="prevPage" :disabled="state.page === 1">上一页</button>
          <text class="page-info">第 {{ state.page }} 页 / 共 {{ state.totalPages }} 页</text>
          <button @click="nextPage" :disabled="state.page >= state.totalPages">下一页</button>
          <text class="total-info">共 {{ state.total }} 条结果</text>
        </view>
    </view>

    <!-- 加载指示器 -->
    <uni-load-more v-if="state.loading" status="loading"></uni-load-more>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'

// 使用 reactive 定义响应式数据，避免模板中的迭代问题
const state = reactive({
  selectedSeason: '全年',
  peopleCount: 2,
  selectedPreference: '购物',
  budget: 1000,
  page: 1,
  size: 5,
  loading: false,
  recommendations: [],
  total: 0,
  totalPages: 0
})

// 季节选项
const seasonOptions = ref(['春季', '夏季', '秋季', '冬季', '全年'])

// 偏好标签选项
const preferenceTags = ref([
  { label: '海滨度假', value: '海滨度假' },
  { label: '历史古迹', value: '历史古迹' },
  { label: '亲子游玩', value: '亲子游玩' },
  { label: '自然风光', value: '自然风光' },
  { label: '美食', value: '美食' },
  { label: '购物', value: '购物' }
])

// 方法定义
const bindSeasonChange = (e) => {
  state.selectedSeason = seasonOptions.value[e.detail.value]
}

const changePeopleCount = (delta) => {
  const newValue = state.peopleCount + delta
  if (newValue >= 1 && newValue <= 10) {
    state.peopleCount = newValue
  }
}

const selectPreference = (value) => {
  state.selectedPreference = value
}

const generatePlan = async () => {
  state.loading = true;
  
  try {
    // 构造请求参数
    const requestData = {
      preferenceType: state.selectedPreference,
      travelTime: state.selectedSeason,
      budget: Number(state.budget),
      peopleCount: state.peopleCount,
      page: state.page,
      size: state.size,
    };

    console.log('发送请求数据:', requestData);

    // 发送请求 - 使用Promise方式避免解构赋值问题
    const result = await new Promise((resolve, reject) => {
      uni.request({
        url: 'http://192.168.165.171:8080/api/recommendations/itineraries',
        method: 'POST',
        data: requestData,
        header: {
          'Content-Type': 'application/json',
        },
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });

    console.log('后端返回数据:', result.data);

    // 处理响应数据
    if (result.statusCode === 200) {
      const responseData = result.data;
      
      // 检查响应数据结构
      if (!responseData) {
        throw new Error('响应数据为空');
      }
      
      console.log('响应数据类型:', typeof responseData);
      console.log('完整响应数据:', JSON.stringify(responseData, null, 2));
      
      // 安全地获取content字段
      let content = [];
      if (responseData.content) {
        if (Array.isArray(responseData.content)) {
          content = responseData.content;
        } else {
          console.warn('content不是数组:', responseData.content);
          content = [];
        }
      } else {
        console.warn('responseData中没有content字段');
        content = [];
      }
      
      console.log('处理后的content:', content);
      
      // 设置状态
      state.recommendations = content;
      state.total = responseData.total || 0;
      state.totalPages = responseData.totalPages || 0;
      state.page = responseData.page || 1;
      state.size = responseData.size || 5;
      
      console.log('成功设置推荐数据:', state.recommendations);
      console.log('设置后的状态:', {
        recommendations: state.recommendations,
        total: state.total,
        totalPages: state.totalPages,
        page: state.page
      });
      
      if (content.length > 0) {
        uni.showToast({
          title: `找到${state.total}条推荐行程`,
          icon: 'success',
          duration: 2000
        });
      } else {
        uni.showToast({
          title: '暂无推荐行程',
          icon: 'none',
          duration: 2000
        });
      }
    } else {
      throw new Error(`请求失败: ${result.data?.message || `状态码: ${result.statusCode}`}`);
    }
  } catch (error) {
    console.error('请求失败:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
    
    uni.showToast({
      title: error.message || '请求失败，请稍后重试',
      icon: 'none',
      duration: 3000
    });
    
    // 清空结果
    state.recommendations = [];
    state.total = 0;
    state.totalPages = 0;
  } finally {
    state.loading = false;
  }
};

const prevPage = () => {
  if (state.page > 1) {
    state.page--;
    generatePlan();
  }
}

const nextPage = () => {
  if (state.page < state.totalPages) {
    state.page++;
    generatePlan();
  }
}

const goBack = () => {
  uni.navigateBack({
    delta: 1,
    fail: (err) => {
      console.error('返回失败:', err);
      uni.showToast({
        title: '返回失败',
        icon: 'error'
      });
    }
  });
}
</script>

<style lang="scss">
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40rpx;
  flex-wrap: wrap;
  
  button {
    margin: 0 10rpx;
    padding: 12rpx 25rpx;
    background: #4a8cff;
    color: white;
    border-radius: 8rpx;
    font-size: 28rpx;
    border: none;
    
    &[disabled] {
      background: #ccc;
      opacity: 0.6;
    }
    
    &::after {
      border: none;
    }
  }
  
  .page-info {
    font-size: 28rpx;
    color: #333;
    margin: 0 15rpx;
  }
  
  .total-info {
    width: 100%;
    text-align: center;
    font-size: 24rpx;
    color: #666;
    margin-top: 15rpx;
  }
}

.recommend-container {
  padding: 20rpx;
  min-height: 100vh;
  background: #f5f7fa;
  position: relative;
  padding-bottom: 40rpx;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #4a8cff 0%, #6ba3ff 100%);
  border-radius: 50%;
  box-shadow: 0 8rpx 20rpx rgba(74, 140, 255, 0.3);
  position: fixed;
  top: 60rpx;
  left: 30rpx;
  z-index: 100;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 4rpx 12rpx rgba(74, 140, 255, 0.2);
  }
}

.header {
  padding: 80rpx 0 30rpx;
  text-align: center;
  .title {
    display: block;
    font-size: 42rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 40rpx;
  .label {
    display: block;
    font-size: 30rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: 500;
  }
  .input {
    border: 1rpx solid #eee;
    padding: 20rpx;
    border-radius: 8rpx;
    color: #333;
    background: #f9f9f9;
  }
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  
  radio {
    margin-right: 15rpx;
    transform: scale(0.9);
  }
}

.number-selector {
  display: flex;
  align-items: center;
  
  .btn-minus, .btn-plus {
    width: 60rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    background: #f0f0f0;
    border-radius: 50%;
    font-size: 32rpx;
    color: #666;
    border: none;
    padding: 0;
    
    &::after {
      border: none;
    }
    
    &:active {
      background: #e0e0e0;
    }
  }
  
  .number {
    margin: 0 30rpx;
    min-width: 120rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
  }
}

.budget-input {
  border: 1rpx solid #eee;
  padding: 20rpx;
  border-radius: 8rpx;
  color: #333;
  background: #f9f9f9;
  width: 100%;
}

.generate-btn {
  background: linear-gradient(135deg, #4a8cff 0%, #6ba3ff 100%);
  color: white;
  border-radius: 50rpx;
  padding: 25rpx;
  font-size: 32rpx;
  margin: 40rpx 0;
  border: none;
  box-shadow: 0 8rpx 20rpx rgba(74, 140, 255, 0.3);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(74, 140, 255, 0.2);
  }
  
  &::after {
    border: none;
  }
}

.result-container {
  .section-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    margin: 30rpx 0 20rpx;
    color: #333;
    padding-left: 10rpx;
    border-left: 6rpx solid #4a8cff;
  }
}

.plan-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  .plan-title {
    font-size: 34rpx;
    font-weight: bold;
    margin-bottom: 25rpx;
    color: #4a8cff;
    display: block;
    padding-bottom: 15rpx;
    border-bottom: 1rpx solid #eee;
  }
}

.plan-detail {
  .detail-item {
    margin-bottom: 20rpx;
    display: flex;
    
    .detail-label {
      font-weight: bold;
      color: #333;
      width: 120rpx;
      flex-shrink: 0;
    }
    
    .detail-content {
      flex: 1;
      color: #666;
    }
  }
}

.cost-info {
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx dashed #eee;
  display: flex;
  align-items: center;
  
  .cost-label {
    font-weight: bold;
    color: #333;
  }
  
  .cost-value {
    color: #ff4a4a;
    font-weight: bold;
    margin: 0 10rpx 0 20rpx;
  }   
  
  .cost-people {
    color: #666;
    font-size: 26rpx;
  }
}
</style>